package test19.outputstream_;

import org.testng.annotations.Test;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream01 {
    public static void main(String[] args) {
    }

    //写入单个字节
    @Test
    public void writeFileOne() throws IOException {
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //new FileOutputStream(filePath) 创建方式，当写入内容是，会覆盖原来的内容
            //fileOutputStream = new FileOutputStream(filePath);
            //new FileOutputStream(filePath, true) 创建方式，当写入内容是，是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath,true);
            //写入一个字节
            fileOutputStream.write('H');
            System.out.println("成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fileOutputStream.close();
        }
    }
    //写入多个字节
    @Test
    public void writeFileTwo(){
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(filePath);
            String fileDate = "hello,world";
            //str.getBytes() 可以把 字符串-> 字节数组
            fileOutputStream.write(fileDate.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    @Test
    public void writeFileThree(){
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(filePath);
            String str = "hello,world";
           //write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
            fileOutputStream.write(str.getBytes(),0,5);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
